// 引入接口文件
import {
    getDetail,
    update,
    create,
    queryAllAddress,
    getRegion,
  } from './integralManagementDetail_cloudServ.js'
  import Cookie from 'js-cookie'
  // 导入项目全局配置文件
import config from 'config/config'
  // 对象和JSON字符串互转
  import { parse } from 'qs'
  // 弹出消息框
  import { message } from 'antd'
  // 日期处理对象
  import moment from 'moment'
  /*isEmpty 对象是否为空
   *isArray 对象是否数组
   *cloneDeep 对象深拷贝
   */
  import { isEmpty, isArray, cloneDeep, merge, pick } from 'lodash'
  // 引入路由对象
  import { hashHistory } from 'dva/router'
  import AppBus from 'utils/bus'
  import { makeAddress } from "utils/util"

  // 初始默认状态
const defultState = {
    id:'',
    loading: false,
    btnLoading: false,
    medias:[],
    pageType: '',
    isClone:false,
    regionList:[],
    areaList: [],//省市区列表
    selectAddressList:[],//选中的项目地址列表
    merchantList: [],//商家
    merchandiseList: [], //商品类型
    formData: {
        "giftName":'',
        "giftJj":'',
        "regionId":'',
        "regionName":'',
        "issj":'',
        "imgUrl":"",
        "integral":0,
        "sumLimit":0,
        "isPost":"",
        "remark":"",
        "projectList":[],
        jfMerchantId: '',//商家id
        jfMerchandiseId:'',//商品类别id
        jfMerchantName:'',//商家名称
        jfMerchandiseName:'',//商品类别名称
        isUnion: '',//是否商家联盟//0否1是
        "stock": null,
    },
    roleArea:[],
    
    query: {
      provinceCodes: ['0'],
      cityCodes: [
          ['0']
      ],
      wholeCountry: true,
  },
  areaList1:[],
  city: [],
  discityList: [],
}

// 声明module
const tmpModule = {
    // namespace: 'secondKillingSetting',
    // 默认状态
    state: cloneDeep(defultState),
    // 入口函数(先执行)
    subscriptions: {
      setup({ dispatch, history }) {
        let clique = localStorage.getItem('clique');
        history.listen(({ pathname, query }) => {
          // 页面路由匹配时执行
          if ('' + tmpModule.pathname === '' + pathname) {
            dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query,clique: localStorage.getItem('clique')} })//每次进去页面先重置状态
            dispatch({ type:'getAreaList', payload: {...query} });
            dispatch({type:'getRegion',payload:{}});
            // dispatch({type:'getMerchant',payload:{}});
            // dispatch({type:'getMerchandise',payload:{}});
            if (query.pageType == 'edit' || query.pageType == 'detail') {
              dispatch({
                type: 'updateStore',
                payload: {
                  pageType: query.pageType,
                  id: query.id,
                  isClone: query.isClone||false,
                }
              })
              // dispatch({
              //   type:'getDetail',
              //   payload:{
              //     id:query.id
              //   }
              // })
            } else {
              dispatch({
                type: 'updateStore',
                payload: {
                  pageType: query.pageType,
                  id: query.id,
                  isClone: query.isClone||false,
                }
              })
            }
          } // end if
        }) // end listen
      },
    },
  
    // 方法列表
    effects: {
      // 查询记录  详情

      //获取详情
  
      // 修改
      *update({ payload }, { put, select, call }) {
        try{
          let {formData, medias,selectAddressList,query} = yield select(state => state[tmpModule.namespace]);
          for(let item in formData){
            if("id,giftName,giftJj,regionId,regionName,issj,imgUrl,integral,sumLimit,isPost,remark,projectList,jfMerchantId,jfMerchandiseId,jfMerchantName,jfMerchandiseName,isUnion,stock".indexOf(item) == -1){
              delete formData[item];
            }
          };
          if(medias.length > 0){
            formData.imgUrl = "";
            medias.map((item,idx)=>{
              if(idx > 0){
                formData.imgUrl += ",";
              }
              formData.imgUrl += item;
            });
          }
          if(selectAddressList.length > 0){
            formData.projectList = [];
            selectAddressList.map((item,idx)=>{
              let p = {
                cityCode:item.cityCode,
                estatePhone:item.estatePhone,
                latitude:item.latitude,
                longitude:item.longitude,
                projectAddr:item.mapAddress,
                projectName:item.productName,
                projectId:item.productId
              }
              formData.projectList.push(p);
            });
          }
          formData.stock = parseInt(formData.stock)
          const userName = Cookie.get(config.cookie.userName);
          formData.updatePerson = userName;
          formData.cityCodes = query.cityCodes
          formData.wholeCountry = query.wholeCountry
          formData.provinceCodes = query.provinceCodes
          const { success, msg } = yield call(update, { ...formData })
          if(success){
            message.success('编辑成功');
            hashHistory.push('/home/integralMall_cloud/integralManagement_cloud')
            yield put({ type: 'updateStore',payload:{btnLoading:false}})
          }else{
            message.error(msg);
          }
        }catch(e){
          console.log(e)
        }
      },
      // 新增
      *create({ payload }, { put, select, call }) {
        try{
          let {formData, medias,selectAddressList,query} = yield select(state => state[tmpModule.namespace])
          
          if(medias.length > 0){
            formData.imgUrl = "";
            medias.map((item,idx)=>{
              if(idx > 0){
                formData.imgUrl += ",";
              }
              formData.imgUrl += item;
            });
          }
          
          if(selectAddressList.length > 0){
            formData.projectList = [];
            selectAddressList.map((item,idx)=>{
              let p = {
                cityCode:item.cityCode,
                estatePhone:item.estatePhone,
                latitude:item.latitude,
                longitude:item.longitude,
                projectAddr:item.mapAddress,
                projectName:item.productName,
                projectId:item.productId
              }
              formData.projectList.push(p);
            });
          }
          formData.stock = parseInt(formData.stock)
          const userName = Cookie.get(config.cookie.userName);
          formData.creator = userName;
          formData.cityCodes = query.cityCodes
          formData.wholeCountry = query.wholeCountry
          formData.provinceCodes = query.provinceCodes
          const { success, msg } = yield call(create, { ...formData })
          if(success){
            message.success('新增成功');
            hashHistory.push('/home/integralMall_cloud/integralManagement_cloud')
            yield put({ type: 'updateStore',payload:{btnLoading:false}})
          }else{
            message.error(msg);
          }
        }catch(e){
          console.log(e)
        }
      },
      *getRegion({ payload }, { put, call, select }) {
        try {
          let {success,rows} = yield call(getRegion, {...payload.params })
          if (success) {
            let regionList = rows
              regionList.forEach((item,index)=>{
                        item.value = item.regionId
                        item.label = item.regionName
                        item.key = index
              })
            yield put({ type: 'updateStore', payload: { regionList } })
          }
        } catch (e) {
        }
      },
      // *getMerchant({ payload }, { put, call, select }) {
      //     let {merchantList} = yield select(state => state[tmpModule.namespace])
      //     let params = {uid:localStorage.getItem("username"),regionId:Cookie.get(config.cookie.regionId)}
      //     let {success,rows} = yield call(getMerchant, params)
      //     if (success) {
      //       let list = rows
      //       merchantList = list.map((item,index)=>{
      //             return {
      //               label: item.name,
      //               value: item.id,
      //               key: index
      //             }
      //         })
      //       yield put({ type: 'updateStore', payload: { merchantList } })
      //     }
      // },
      // *getMerchandise({ payload }, { put, call, select }) {
      //     let {merchandiseList} = yield select(state => state[tmpModule.namespace])
      //     let params = {uid:localStorage.getItem("username"),regionId:Cookie.get(config.cookie.regionId)}
      //     let {success,rows} = yield call(getMerchandise, params)
      //     if (success) {
      //       let list = rows
      //       merchandiseList = list.map((item,index)=>{
      //             return {
      //               label: item.typeName,
      //               value: item.id,
      //               key: index
      //             }
      //         })
      //       yield put({ type: 'updateStore', payload: { merchandiseList } })
      //     }
      // },
      *getDetail({payload},{put,call,select}){
        let {medias,selectAddressList,query,roleArea,areaList1,city} = yield select(state => state[tmpModule.namespace])
       try{
        let {data,success}=yield call(getDetail,payload)
        // 
        if(success){
          if(data.imgUrl && data.imgUrl != ""){
              medias = data.imgUrl.split(",");
          }
          if(data.projectList && data.projectList.length > 0){
            data.projectList.map((item,idx)=>{
              let p = {
                cityCode:item.cityCode,
                estatePhone:item.estatePhone,
                latitude:item.latitude,
                longitude:item.longitude,
                projectAddr:item.mapAddress,
                projectName:item.productName,
                projectId:item.productId,
                mapAddress:item.projectAddr,
                productName:item.projectName,
                productId:item.projectId,
              };
              selectAddressList.push(p);
            });
          }
          if(data.wholeCountry){
            data.provinceCodes=['0']
            data.cityCodes = [['0']]
          } else {
            for(var i=0;i<data.provinceCodes.length;i++){
              // console.log(query.provinceCodes[i])
              if(roleArea.indexOf(data.provinceCodes[i])==-1){
                delete data.provinceCodes[i]
              }
              for(var y=0;y<areaList1.length;y++){
                // console.log(areaList1[y])
                if(data.provinceCodes[i]==areaList1[y].value){
                  city[i]=areaList1[y].children
                  // console.log(areaList1[y])
                }
              }
              city.map(item=>{
                item.map(child=>{
                  child.disabled = true;
                })
              })
            }
          }
          // query.cityCodes[0] = data.cityCodes
          
          yield put({
            type:'updateStore',
            payload:{
              city,
              query:JSON.parse(JSON.stringify(data)),
              formData:data,
              medias,
              selectAddressList
            }
          })
        }
       }catch(err){
         console.log(err)
       }
        
      },
      *getAreaList({ payload }, { put, call, select }) {
          try {
              let {poageType,slideshowId,clique}=yield select((state)=>state[tmpModule.namespace])
              const { success, data } = yield call(queryAllAddress, {})
              if (success) {
                  //todo: 接口格式调整后删除
                  let areaList = []
                  let arr = []
                  data.map((item,index)=>{
                    arr.push(item.value)
                  })
                  let areaList1 = []
                  if(JSON.parse(clique)){
                    let arr = [data[0]]
                    let attr = [data[data.length-1]]
                    data[0] = {
                      label:"北京",
                      value:"110100",
                      children:arr
                    }
                    data[data.length-1]={
                      label:"澳门",
                      value:"820000",
                      children:attr
                    }
                  }
                  //console.log(data,"data")
                  //去掉第三级，
                  areaList = makeAddress(data, 2, false)
                  areaList1 = makeAddress(data, 2)
                  areaList1 = data
                  areaList1.shift()
                  yield put({ type: 'updateStore', payload: { roleArea:arr,areaList:areaList,areaList1: areaList1,} })
                  if(payload.pageType=='detail'|| payload.pageType=='edit'){
                    yield put({type: 'getDetail', payload: {id:payload.id}})
                 }
              }
          } catch (e) {
          }
      },
    },
    // 存入状态机
    reducers: {
      updateStore(preState, action) {
        return Object.assign({}, preState, action.payload)
      },
    }
  }
  
  export default tmpModule